#!/bin/sh

. /usr/share/common

GPIO_FILE="/etc/gpio.conf"
[ -f "$GPIO_FILE" ] || die "GPIO configuration file not found: $GPIO_FILE"

VALID_STATES="high low input"

# TODO: Set the maximum GPIO number by SOC model
MAX_GPIO=192

start() {
	echo_title "Setting GPIOs"

	while IFS= read -r line; do
		# Skip empty lines and comments
		[ -z "$line" ] || echo "$line" | grep -q '^#' && continue

		# Extract fields and validate
		set -- $line
		gpionum=$1
		state=$(echo "$2" | tr A-Z a-z)
		case "$VALID_STATES" in
			*"$state"*)
				# pin is in valid range
				if [ "$gpionum" -lt 0 ] || [ "$gpionum" -gt $MAX_GPIO ]; then
					echo_warning "Invalid GPIO number: $gpionum in line: $line"
				else
					gpio "$state" "$gpionum"
					echo_info "GPIO $gpionum set to $state"

					if [ -n "$3" ]; then
						echo_info "Description: $3"
					fi
				fi
				;;
			*)
				echo_warning "Invalid state: $state in line: $line"
				;;
		esac
	done < $GPIO_FILE
}

case "$1" in
	start)
		start
		;;
	stop)
		true
		;;
	restart)
		start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

exit 0
